package com.wdz.pma.controllers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wdz.pma.dao.ProjectRepository;
import com.wdz.pma.dao.StudentRepository;
import com.wdz.pma.dto.ChartData;
import com.wdz.pma.dto.StudentProject;
import com.wdz.pma.entities.Project;
import com.wdz.pma.entities.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller

public class HomeController {

    @Value("${version}")    //读取全局变量
    private String version;

//    引入Repository的依赖
    @Autowired
    ProjectRepository projectRepository;

    @Autowired
    StudentRepository studentRepository;

    //        渲染主页-【项目】的方法
    @GetMapping("/")
    public String displayHome(Model model) throws JsonProcessingException {

        model.addAttribute("versionNumber", version);
//        调用数据接入层方法findAll()
        List<Project> projects = projectRepository.findAll();
        model.addAttribute("projects", projects);//通过model对象将数据传入视图层（HTML模板）

//        1.调用在ProjectRepository中新编写的用于【查询项目状态的方法】
        List<ChartData> projectStatusData = projectRepository.getProjectStatus();
//        2.转换projectStatusData为JSON结构，便于在js脚本中使用
        ObjectMapper objectMapper = new ObjectMapper();
//      3.无法转化时需要抛出异常↓↓↓   ：方法后加上throws JsonProcessingException
        String jsonString = objectMapper.writeValueAsString(projectStatusData);
//      4.通过model传入视图↓↓↓  :   [{"未开始",1} , {"进行中",1} , {"已完成",1}]
        model.addAttribute("projectStatusData" , jsonString);

        List<StudentProject> studentProjects = studentRepository.studentProjects();
        model.addAttribute("studentProjects", studentProjects);


        List<Student> students = studentRepository.findAll();
        model.addAttribute("students", students);
        return "main/home";
    }

}


